package com.example.tool.util.jt;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.yl.jms.sdk.JtExpressApi;
import com.yl.jms.sdk.auth.ClientConfiguration;
import com.yl.jms.sdk.auth.Digests;
import com.yl.jms.sdk.client.JtExpressApiOperator;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 极兔快递
 */
public class JTApiUtil {
    private static final String PLAIN_PASSWORD = "H5CD3zE6"; // 客户明文密码
    private static final String CUSTOMER_CODE = "5731318";
    private static final String TEMPLATE_CODE = "5731318";
    private static final String API_ACCOUNT = "795641694451109120";
    private static final String PRIVATE_KEY = "a24d9c1d158a4de4b32e363f9aac472c";
    private static final String TEST_URL = "https://uat-openapi.bxexpress.com.cn/webopenplatformapi/api/logistics/trace";
    private static final String PROD_URL = "https://openapi.bxexpress.com.cn/webopenplatformapi/api/logistics/trace";
    private static final String SB_URL = "https://openapi.bxexpress.com.cn/webopenplatformapi/api/trace/subscribe";
    private static final String GO_URL = "https://openapi.bxexpress.com.cn/webopenplatformapi/api/order/getOrders";
    private static final String SM_URL = "https://openapi.jtexpress.com.cn/webopenplatformapi/api/sms/send";
    private static final Pattern TRANSFER_CENTER_MSG_PATTERN = Pattern.compile("(?:快件到达【|快件离开【|快件在【)[^】]*转运中心】");
    private static JtExpressApi jtExpressApi = null;

    static {
        ClientConfiguration clientConfiguration = new ClientConfiguration(API_ACCOUNT, PRIVATE_KEY);
        clientConfiguration.setCustomerCode(null);
        clientConfiguration.setCustomerPwd(null);
    }

    public static JtExpressApi getClient() {
        if (ObjectUtil.isNull(jtExpressApi)) {
            ClientConfiguration clientConfiguration = new ClientConfiguration(API_ACCOUNT, PRIVATE_KEY);
            clientConfiguration.setCustomerCode(null);
            clientConfiguration.setCustomerPwd(null);
            jtExpressApi = new JtExpressApiOperator(clientConfiguration);
        }
        return jtExpressApi;
    }

/*    public static void main(String[] args) {
        try {
            // 要查询的运单号，多个用逗号分隔
            String billCodes = "JT5376115398920";
            JSONObject result = queryLogistics(billCodes, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    public static JSONObject queryLogistics(String waybillNo) {
        Map<String, Object> map = new HashMap<>();
        map.put("billCodes", waybillNo);
        JSONObject location = null;
        try {
            location = getClient().post(map, PROD_URL);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return location;
    }

    public static JSONObject trackSubSubscribe(String waybillNo) {
        Map<String, Object> bizContent = new HashMap<>();
        Map<String, Object> item = new HashMap<>();
        item.put("traceNode", "1&2&3&4&5&6&7&8&9&10&11&12&13&14");
        item.put("waybillCode", waybillNo);
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(item);
        bizContent.put("id", API_ACCOUNT);
        bizContent.put("list", list);
        JSONObject location = null;
        try {
            location = getClient().post(bizContent, SB_URL);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return location;
    }

    public static JSONObject getOrders(String waybillNo) {
        // 1. 构建业务参数
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("customerCode", CUSTOMER_CODE);
        bizParams.put("command", 2); // 按客户订单编号查询
        bizParams.put("serialNumber", Arrays.asList(waybillNo)); // 客户订单号列表
        // 生成业务参数签名
        String bizDigest = Digests.digestForBizParam(CUSTOMER_CODE, PLAIN_PASSWORD, PRIVATE_KEY);
        bizParams.put("digest", bizDigest);
        String bizContent = JSONObject.toJSONString(bizParams);
        // 2. 生成Header签名
        long timestamp = System.currentTimeMillis();
        String headDigest = Digests.digestForHead(bizContent, PRIVATE_KEY);
        // 3. 发送请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(GO_URL);
        // 设置Headers
        httpPost.setHeader("apiAccount", API_ACCOUNT);
        httpPost.setHeader("digest", headDigest);
        httpPost.setHeader("timestamp", String.valueOf(timestamp));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // 设置Body (x-www-form-urlencoded)
        StringEntity entity = null;
        try {
            entity = new StringEntity("bizContent=" + URLEncoder.encode(bizContent, "UTF-8"));
            httpPost.setEntity(entity);
            // 4. 获取响应
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            return JSONObject.parseObject(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isInTransferCenter(String text) {
        if (text == null) {
            return false;
        }
        Matcher matcher = TRANSFER_CENTER_MSG_PATTERN.matcher(text);
        return matcher.find();
    }

    public static JSONObject smsSend(String waybillNo, String[] params) {
        // 1. 构建业务参数
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("type", TEMPLATE_CODE);
        bizParams.put("params", params); // 按客户订单编号查询
        bizParams.put("waybillNo", waybillNo); // 客户订单号列表
        // 生成业务参数签名
//        String bizDigest = Digests.digestForBizParam(CUSTOMER_CODE, PLAIN_PASSWORD, PRIVATE_KEY);
//        bizParams.put("digest", bizDigest);
        String bizContent = JSONObject.toJSONString(bizParams);
        // 2. 生成Header签名
        long timestamp = System.currentTimeMillis();
        String headDigest = Digests.digestForHead(bizContent, PRIVATE_KEY);
        // 3. 发送请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(SM_URL);
        // 设置Headers
        httpPost.setHeader("apiAccount", API_ACCOUNT);
        httpPost.setHeader("digest", headDigest);
        httpPost.setHeader("timestamp", String.valueOf(timestamp));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // 设置Body (x-www-form-urlencoded)
        StringEntity entity = null;
        try {
            entity = new StringEntity("bizContent=" + URLEncoder.encode(bizContent, "UTF-8"));
            httpPost.setEntity(entity);
            // 4. 获取响应
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            return JSONObject.parseObject(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        //   out of stock
//        String[] params= new String[]{"测试短信","12000元"};
//        System.out.println(smsSend("JT3126691231074",params));
        System.out.println(getOrders("JT5392463682197"));
    }

}
